{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pprint\n",
    "from duckduckgo_search import DDGS\n",
    "from typing import List, Dict, Any, Optional\n",
    "import logging\n",
    "from autogen import ConversableAgent"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"../secret/openai.txt\", \"r\") as f:\n",
    "    OPENAI_API_KEY = f.read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "MODEL = \"gpt-4o-mini\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "global current_search_result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def duckduckgo_search(search_term: str, max_results: int = 5) -> Optional[List[Dict[str, Any]]]:\n",
    "    \"\"\"\n",
    "    Perform a DuckDuckGo search and return a list of results.\n",
    "\n",
    "    Args:\n",
    "        search_term (str): The term to search for.\n",
    "        max_results (int, optional): The maximum number of search results to return. Defaults to 5.\n",
    "\n",
    "    Returns:\n",
    "        Optional[List[Dict[str, Any]]]: A list of dictionaries containing the search results, or None if an error occurs.\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # Perform the search using DuckDuckGo\n",
    "        results = DDGS().text(search_term, max_results=max_results)\n",
    "        \n",
    "        # Return the search results\n",
    "        return results\n",
    "    \n",
    "    except Exception as e:\n",
    "        logging.error(f\"An error occurred during the DuckDuckGo search: {e}\")\n",
    "        return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"quantum computing\"\n",
    "\n",
    "result = duckduckgo_search(query, max_results=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'body': 'Learn about quantum computing, a computer that exploits quantum '\n",
      "          'mechanical phenomena to perform calculations faster than classical '\n",
      "          'computers. Explore the history, algorithms, technologies, and '\n",
      "          'applications of quantum computing, as well as the obstacles and '\n",
      "          'opportunities it faces.',\n",
      "  'href': 'https://en.wikipedia.org/wiki/Quantum_computing',\n",
      "  'title': 'Quantum computing - Wikipedia'},\n",
      " {'body': 'Quantum computing is an emergent field of cutting-edge computer '\n",
      "          'science harnessing the unique qualities of quantum mechanics to '\n",
      "          'solve problems beyond the ability of even the most powerful '\n",
      "          'classical computers. The field of quantum computing contains a '\n",
      "          'range of disciplines, including quantum hardware and quantum '\n",
      "          'algorithms.',\n",
      "  'href': 'https://www.ibm.com/topics/quantum-computing',\n",
      "  'title': 'What Is Quantum Computing? | IBM'}]\n"
     ]
    }
   ],
   "source": [
    "pprint.pprint(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Agents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Roles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "assistant = ConversableAgent(\n",
    "    name=\"Assistant_Search_Engine\", # must comply with naming rules\n",
    "    system_message=\"You are a helpful assistant. \"\n",
    "    \"You will help search using a search engine. You will suggest one best search term. \"\n",
    "    \"Follow the user's instruction on number of search websites to return. \"\n",
    "    \"If the number is not spcified, use max_results=5 as a default. \"\n",
    "    \"Return 'TERMINATE' when the task is done.\",\n",
    "    llm_config={\"config_list\": [{\n",
    "        \"model\": MODEL, \n",
    "        \"api_key\": OPENAI_API_KEY,}]},\n",
    "    max_consecutive_auto_reply=1,\n",
    "    human_input_mode=\"NEVER\",\n",
    ")\n",
    "\n",
    "user_proxy = ConversableAgent(\n",
    "    name=\"User Proxy\",\n",
    "    llm_config=None,\n",
    "    human_input_mode=\"NEVER\",\n",
    "    is_termination_msg=lambda msg: msg.get(\"content\") is not None and \"TERMINATE\" in msg[\"content\"],\n",
    "    max_consecutive_auto_reply=3\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tool registration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function __main__.duckduckgo_search(search_term: str, max_results: int = 5) -> Optional[List[Dict[str, Any]]]>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "assistant.register_for_llm(name=\"duckduckgo_search\",\n",
    "                           description=\"search engine from DuckDuckGO\"\n",
    "                           )(duckduckgo_search)\n",
    "\n",
    "user_proxy.register_for_execution(name=\"duckduckgo_search\",\n",
    "                                 )(duckduckgo_search)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'type': 'function',\n",
       "  'function': {'description': 'search engine from DuckDuckGO',\n",
       "   'name': 'duckduckgo_search',\n",
       "   'parameters': {'type': 'object',\n",
       "    'properties': {'search_term': {'type': 'string',\n",
       "      'description': 'search_term'},\n",
       "     'max_results': {'type': 'integer',\n",
       "      'default': 5,\n",
       "      'description': 'max_results'}},\n",
       "    'required': ['search_term']}}}]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "assistant.llm_config['tools']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We assigned `register_for_execution` to `user_proxy` because it's two-agent conversation. They take turn.\n",
    "1. `user_proxy` asks for search\n",
    "2. `assistant` suggests how to 'call' (or search)\n",
    "3. `user_proxy` does the actual search and gets results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conversation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mUser Proxy\u001b[0m (to Assistant_Search_Engine):\n",
      "\n",
      "search about quantum computing\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mAssistant_Search_Engine\u001b[0m (to User Proxy):\n",
      "\n",
      "\u001b[32m***** Suggested tool call (call_V6xkt01UMKXrzPvMKMkTxee7): duckduckgo_search *****\u001b[0m\n",
      "Arguments: \n",
      "{\"search_term\":\"quantum computing\",\"max_results\":5}\n",
      "\u001b[32m**********************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION duckduckgo_search...\u001b[0m\n",
      "\u001b[33mUser Proxy\u001b[0m (to Assistant_Search_Engine):\n",
      "\n",
      "\u001b[33mUser Proxy\u001b[0m (to Assistant_Search_Engine):\n",
      "\n",
      "\u001b[32m***** Response from calling tool (call_V6xkt01UMKXrzPvMKMkTxee7) *****\u001b[0m\n",
      "[{\"title\": \"Quantum computing - Wikipedia\", \"href\": \"https://en.wikipedia.org/wiki/Quantum_computing\", \"body\": \"Learn about the origins, concepts and developments of quantum computing, a field that exploits quantum mechanical phenomena for faster and more efficient calculations. Explore the applications, limitations and controversies of quantum algorithms, qubits, encryption and simulation.\"}, {\"title\": \"What Is Quantum Computing? | IBM\", \"href\": \"https://www.ibm.com/topics/quantum-computing\", \"body\": \"Quantum computing is an emergent field of cutting-edge computer science harnessing the unique qualities of quantum mechanics to solve problems beyond the ability of even the most powerful classical computers. The field of quantum computing contains a range of disciplines, including quantum hardware and quantum algorithms.\"}, {\"title\": \"Explainer: What is a quantum computer? | MIT Technology Review\", \"href\": \"https://www.technologyreview.com/2019/01/29/66141/what-is-quantum-computing/\", \"body\": \"Learn how quantum computers use qubits, superposition, entanglement, and algorithms to perform calculations beyond the reach of classical machines. Find out where quantum computers are likely to be most useful first and what challenges they face.\"}, {\"title\": \"What Is Quantum Computing? - Caltech Science Exchange\", \"href\": \"https://scienceexchange.caltech.edu/topics/quantum-science-explained/quantum-computing-computers\", \"body\": \"Learn what quantum computing is, how it works, and why it matters from Caltech researchers who have made breakthroughs in the field. Find out the challenges and opportunities of developing and using quantum computers for various applications.\"}, {\"title\": \"What Is Quantum Computing? The Complete WIRED Guide | WIRED\", \"href\": \"https://www.wired.com/story/wired-guide-to-quantum-computing/\", \"body\": \"And quantum computing is about chasing perhaps the biggest performance boost in the history of technology. The basic idea is to smash some barriers that limit the speed of existing computers by ...\"}]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "chat_result = user_proxy.initiate_chat(\n",
    "    assistant,\n",
    "    message=\"search about quantum computing\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'content': 'search about quantum computing', 'role': 'assistant'},\n",
       " {'tool_calls': [{'id': 'call_V6xkt01UMKXrzPvMKMkTxee7',\n",
       "    'function': {'arguments': '{\"search_term\":\"quantum computing\",\"max_results\":5}',\n",
       "     'name': 'duckduckgo_search'},\n",
       "    'type': 'function'}],\n",
       "  'content': None,\n",
       "  'role': 'assistant'},\n",
       " {'content': '[{\"title\": \"Quantum computing - Wikipedia\", \"href\": \"https://en.wikipedia.org/wiki/Quantum_computing\", \"body\": \"Learn about the origins, concepts and developments of quantum computing, a field that exploits quantum mechanical phenomena for faster and more efficient calculations. Explore the applications, limitations and controversies of quantum algorithms, qubits, encryption and simulation.\"}, {\"title\": \"What Is Quantum Computing? | IBM\", \"href\": \"https://www.ibm.com/topics/quantum-computing\", \"body\": \"Quantum computing is an emergent field of cutting-edge computer science harnessing the unique qualities of quantum mechanics to solve problems beyond the ability of even the most powerful classical computers. The field of quantum computing contains a range of disciplines, including quantum hardware and quantum algorithms.\"}, {\"title\": \"Explainer: What is a quantum computer? | MIT Technology Review\", \"href\": \"https://www.technologyreview.com/2019/01/29/66141/what-is-quantum-computing/\", \"body\": \"Learn how quantum computers use qubits, superposition, entanglement, and algorithms to perform calculations beyond the reach of classical machines. Find out where quantum computers are likely to be most useful first and what challenges they face.\"}, {\"title\": \"What Is Quantum Computing? - Caltech Science Exchange\", \"href\": \"https://scienceexchange.caltech.edu/topics/quantum-science-explained/quantum-computing-computers\", \"body\": \"Learn what quantum computing is, how it works, and why it matters from Caltech researchers who have made breakthroughs in the field. Find out the challenges and opportunities of developing and using quantum computers for various applications.\"}, {\"title\": \"What Is Quantum Computing? The Complete WIRED Guide | WIRED\", \"href\": \"https://www.wired.com/story/wired-guide-to-quantum-computing/\", \"body\": \"And quantum computing is about chasing perhaps the biggest performance boost in the history of technology. The basic idea is to smash some barriers that limit the speed of existing computers by ...\"}]',\n",
       "  'tool_responses': [{'tool_call_id': 'call_V6xkt01UMKXrzPvMKMkTxee7',\n",
       "    'role': 'tool',\n",
       "    'content': '[{\"title\": \"Quantum computing - Wikipedia\", \"href\": \"https://en.wikipedia.org/wiki/Quantum_computing\", \"body\": \"Learn about the origins, concepts and developments of quantum computing, a field that exploits quantum mechanical phenomena for faster and more efficient calculations. Explore the applications, limitations and controversies of quantum algorithms, qubits, encryption and simulation.\"}, {\"title\": \"What Is Quantum Computing? | IBM\", \"href\": \"https://www.ibm.com/topics/quantum-computing\", \"body\": \"Quantum computing is an emergent field of cutting-edge computer science harnessing the unique qualities of quantum mechanics to solve problems beyond the ability of even the most powerful classical computers. The field of quantum computing contains a range of disciplines, including quantum hardware and quantum algorithms.\"}, {\"title\": \"Explainer: What is a quantum computer? | MIT Technology Review\", \"href\": \"https://www.technologyreview.com/2019/01/29/66141/what-is-quantum-computing/\", \"body\": \"Learn how quantum computers use qubits, superposition, entanglement, and algorithms to perform calculations beyond the reach of classical machines. Find out where quantum computers are likely to be most useful first and what challenges they face.\"}, {\"title\": \"What Is Quantum Computing? - Caltech Science Exchange\", \"href\": \"https://scienceexchange.caltech.edu/topics/quantum-science-explained/quantum-computing-computers\", \"body\": \"Learn what quantum computing is, how it works, and why it matters from Caltech researchers who have made breakthroughs in the field. Find out the challenges and opportunities of developing and using quantum computers for various applications.\"}, {\"title\": \"What Is Quantum Computing? The Complete WIRED Guide | WIRED\", \"href\": \"https://www.wired.com/story/wired-guide-to-quantum-computing/\", \"body\": \"And quantum computing is about chasing perhaps the biggest performance boost in the history of technology. The basic idea is to smash some barriers that limit the speed of existing computers by ...\"}]'}],\n",
       "  'role': 'tool'}]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chat_result.chat_history"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'usage_including_cached_inference': {'total_cost': 3.51e-05,\n",
       "  'gpt-4o-mini-2024-07-18': {'cost': 3.51e-05,\n",
       "   'prompt_tokens': 134,\n",
       "   'completion_tokens': 25,\n",
       "   'total_tokens': 159}},\n",
       " 'usage_excluding_cached_inference': {'total_cost': 0}}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chat_result.cost"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "autogen",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
